package com.lzx.dormsys.controller;

import com.github.pagehelper.PageInfo;
import com.lzx.dormsys.bean.RoleGroupBean;
import com.lzx.dormsys.bean.RoleGroupMenusBeanKey;
import com.lzx.dormsys.core.AjaxResult;
import com.lzx.dormsys.entity.GroupRequest;
import com.lzx.dormsys.service.MenuService;
import com.lzx.dormsys.service.RoleGroupBeanService;
import com.lzx.dormsys.service.RoleGroupMenusService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/RoleGroupAction")
public class RoleGroupAction {
    @Autowired
    MenuService menuService;

    @Autowired
    RoleGroupMenusService roleGroupMenusService;

    @Autowired
    RoleGroupBeanService roleGroupBeanService;

    @PostMapping("/add")
    public AjaxResult addRole(@RequestBody GroupRequest groupRequest){
        RoleGroupBean roleGroupBean = new RoleGroupBean();
        roleGroupBean.setGroupid(groupRequest.getGroupid());
        roleGroupBean.setGroupname(groupRequest.getGroupname());
        roleGroupBean.setDescription(groupRequest.getDescription());
        int insert = roleGroupBeanService.insert(roleGroupBean);
        if (insert<=0){
            return AjaxResult.error("新增失败");
        }
        return AjaxResult.success("新增成功");
    }

    @DeleteMapping("/remove")
    public AjaxResult removeRole(String groupid){
        int i = roleGroupBeanService.deleteByPrimaryKey(groupid);
        return AjaxResult.success("删除成功");
    }

    @GetMapping("/getRoleGroupTree")
    public AjaxResult getRoleGroupTree(String groupid){
        // 1 获得系统中的所有菜单，形成前端可以解析的树
        List<Map<String, Object>> menuList = menuService.queryAllMenus();

        // 2 根据传入的groupid（权限组编号）获得权限组能够访问的菜单的列表（用户在界面中选中相应的节点）
        RoleGroupMenusBeanKey key = new RoleGroupMenusBeanKey();
        key.setGroupid(groupid);
        List<RoleGroupMenusBeanKey> roleGroupMenusList = roleGroupMenusService.queryData(key);

        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("allmenulist",menuList);
        resultMap.put("checkmenulist",roleGroupMenusList);

        return AjaxResult.success(resultMap);
    }

    @GetMapping("/getRoleGroup")
    public AjaxResult getRoleGroup(){
        PageInfo<RoleGroupBean> pageInfo = roleGroupBeanService.queryData(null, 1, 1);
        return AjaxResult.success(pageInfo);
    }

    @PostMapping("/updateRoleGroup")
    public AjaxResult updateRoleGroup(@RequestBody GroupRequest groupRequest){
        try{
            roleGroupBeanService.updateRoleGroup(groupRequest);
        }catch (Exception e){
            System.out.println(e);
            return AjaxResult.error();
        }
        return AjaxResult.success("更新成功！");
    }

}